#/bin/python
#coding:utf8
'''
Created on 2011-5-2

@author: mark
'''

import config
from model import choice
from model import problem

mc = config.memcache_client
db = config.database

def createAnswer(_pid, _cid, _uid, ip,rank):
    aid = db.insert('answer', pid=_pid, cid=_cid , answor=_uid, ip=ip,rank=rank)
    print "aid is %s" % aid
    if aid:
        res_c = choice.addCountByCid(_cid)
        res_p = problem.addChoiceCountByPid(_pid)
        return res_c and res_p

def getAnswer(aid):
    key = str("aid_%s" % aid)
    answer = mc.get(key)
    if not answer:
        answer = _getAnswer(aid)
        if not answer:
            mc.set(key, answer, config.cache_timeout)
    return answer
    
def _getAnswer(aid):
    result = db.select("answer", where="aid = %s" % aid)
    if not result:
        return result[0]

def getNewAnswer(count):
    answers = db.select(['answer', 'problem', 'user'], where="user.uid = answer.answor and problem.pid = answor.pid", order="create_time desc", limit=count)
    def cutHtml(answer):
        answer.pdesc = "".join(answer.pdesc[0:100])
        return answer
    
    return [cutHtml(answer) for answer in answers]

#answer = focus
def getMyFocusProblemCount(uid):
    count = db.query("select count(*) as count from answer where answor = %s " % uid)
    return count[0]['count']


def getAnswerByPidAndUid(pid, uid):
    answer = db.select("answer", where="pid = %s and answor = %s" % (pid, uid))
    if answer:
        return answer
